const schedule = require('node-schedule');
const { Memberships, User, sequelize } = require('../models');
const { Op } = require('sequelize');
const logger = require('../utils/logger');
/**
 * 定时检查并处理过期会员
 * 每小时的第 0 分钟、第 30 分钟执行
 */
const checkMembership = async () => {
  schedule.scheduleJob('0 0 30 * * *', async () => {
    try {
      const t = await sequelize.transaction();
      const expiredUsers = await User.findAll({
        attributes: ['id'],
        where: {
          // role: { [Op.not]: 100 }, //排除管理员
          role: 1, //只选vip用户
          membershipExpiredAt: {
            [Op.lt]: new Date(), // 小于当前时间 },
          },
        },
        transaction: t,
        lock: true, // 使用排它锁，防止并发更新
      });

      const userIdS = expiredUsers.map((i) => i.id);
      await User.update(
        {
          membershipExpiredAt: null,
          role: 1,
        },
        { where: { id: userIdS }, transaction: t }
      );
      await t.commit();
    } catch (error) {
      await t.rollback();
      logger.error('定时任务处理超时订单失败：', error);
    }
  });
};

module.exports = checkMembership;
